package org.mall.modules.pay.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.mall.common.api.vo.CommonResult;
import org.mall.common.constant.CommonConstant;
import org.mall.common.util.DateUtil;
import org.mall.common.util.json.JacksonUtils;
import org.mall.modules.pay.convert.PayNotifyConvert;
import org.mall.modules.pay.convert.PayRefundConvert;
import org.mall.modules.pay.dataobject.PayRefundDO;
import org.mall.modules.pay.dataobject.PayTransactionDO;
import org.mall.modules.pay.dataobject.PayTransactionExtensionDO;
import org.mall.modules.pojo.pay.message.PayTransactionSuccessMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/***
 *@author yinxucun
 *@date 2020-01-13 10:55 
 */
@Component
@Slf4j
public class AliPaySDK extends AbstractPaySDK {

    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private DefaultMQProducer defaultMQProducer;
    @Override
    public CommonResult<?> submitTransaction(PayTransactionDO transaction, PayTransactionExtensionDO transactionExtension, Map<String, Object> extra) {
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();

        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(transaction.getOrderDescription());
        model.setSubject(transaction.getOrderSubject());
        model.setOutTradeNo(transactionExtension.getTransactionCode());
        model.setTimeoutExpress("30m");
        BigDecimal price=new BigDecimal(transaction.getPrice());
        model.setTotalAmount(String.valueOf(price.divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP)));
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(transaction.getNotifyUrl());
        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return  CommonResult.success(response.getBody());
        } catch (AlipayApiException e) {
            log.error("提交支付交易失败:订单编号:{},支付渠道：支付宝,",transaction.getOrderId());
        }

        return null;
    }

    @Override
    public CommonResult<TransactionSuccessBO> parseTransactionSuccessParams(String params) {
        JSONObject jsonObject= JSONObject.parseObject(params);
        String outTradeNo= (String) jsonObject.get("out_trade_no");
        String status= (String) jsonObject.get("trade_status");
        if ("TRADE_SUCCESS".equals(status)){
            TransactionSuccessBO transactionSuccessBO=new TransactionSuccessBO();
            transactionSuccessBO.setPaymentTime(DateUtil.parsDateString((String)jsonObject.get(""),"yyyy-MM-dd HH:mm:ss"));
            transactionSuccessBO.setTradeNo(jsonObject.getString("trade_no"));
            transactionSuccessBO.setTransactionCode(outTradeNo);
            return CommonResult.success(transactionSuccessBO);
        }
        return CommonResult.error("");

    }

    @Override
    public CommonResult<String> submitRefund(PayRefundDO refund, PayTransactionExtensionDO transactionExtension, Map<String, Object> extra) {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("out_trade_no",transactionExtension.getTransactionCode());
        jsonObject.put("out_request_no",refund.getRefundCode());
        BigDecimal price=new BigDecimal(refund.getPrice());
        jsonObject.put("refund_amount",price.divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP));
        request.setBizContent(jsonObject.toJSONString());
        try {
            AlipayTradeRefundResponse response =alipayClient.execute(request);
            if (!response.isSuccess()){
               log.error("退款失败:业务返回代码：{},原因:{}",response.getSubCode(),response.getSubMsg());
               return CommonResult.error("发起退款失败:"+response.getSubMsg());
            }
            defaultMQProducer.setProducerGroup("pay-provider-group-" + PayTransactionSuccessMessage.TOPIC);
            try {
                Message sendMsg = new Message(CommonConstant.UPDATE_ALI_PAY_UPDATE_SUCCESS,
                        "rocketTag",
                        "", JacksonUtils.toJSONString(PayRefundConvert.INSTANCE.convert(refund)).getBytes());
                sendMsg.setDelayTimeLevel(2);
                defaultMQProducer.send(sendMsg);
            } catch (Exception e) {
                log.error("发送到mq失败,退款:{}申请已成功，请稍后刷新",refund.getRefundCode());
                return CommonResult.error("退款申请成功,请稍后刷新");
            }

        } catch (AlipayApiException e) {
            return CommonResult.error("发起退款失败:"+e.getErrMsg());
        }
        return CommonResult.success("SUCCESS");
    }

    @Override
    public CommonResult<RefundSuccessBO> parseRefundSuccessParams(String params) {
        return null;
    }


}
